#include<input_manager.h>





/* socket
 * bind
 * sendto/recvfrom
 */

#define SERVER_PORT 8888

static int g_iSocketServer;

int netDeviceInit(void)
{
	int iRet;
	struct sockaddr_in tSocketServerAddr;

	g_iSocketServer = socket(AF_INET, SOCK_DGRAM, 0);
	if (-1 == g_iSocketServer)
	{
		printf("socket error!\n");
		return -1;
	}

	tSocketServerAddr.sin_family      = AF_INET;
	tSocketServerAddr.sin_port        = htons(SERVER_PORT);  /* host to net, short */
 	tSocketServerAddr.sin_addr.s_addr = INADDR_ANY;
	memset(tSocketServerAddr.sin_zero, 0, 8);
	
	iRet = bind(g_iSocketServer, (const struct sockaddr *)&tSocketServerAddr, sizeof(struct sockaddr));
	if (-1 == iRet)
	{
		printf("bind error!\n");
		return -1;
	}
	
	return 0;
}

int netGetInputEvent(PInputEvent ptInputEvent)
{	
	int iRecvLen;
	char aRecvBuf[1000];
	struct sockaddr_in tSocketClientAddr;

	unsigned int iAddrLen = sizeof(struct sockaddr);
	iRecvLen = recvfrom(g_iSocketServer, aRecvBuf, 999, 0, (struct sockaddr *)&tSocketClientAddr, &iAddrLen);
	if (iRecvLen > 0)
	{
		aRecvBuf[iRecvLen] = '\0';
		ptInputEvent->iType = INPUT_TYPE_NET;
		gettimeofday(&ptInputEvent->tTime, NULL);
		strncpy(ptInputEvent->str,aRecvBuf,1000);
		ptInputEvent->str[999] = '\0';
		return 0;
	}
	return -1;

}


int netDeviceExit(void)
{
	close(g_iSocketServer);
	return 0;
}

static InputDevOpr g_tNetInputOpr = {
	.name          = "net",
	.GetInputEvent = netGetInputEvent,
	.DeviceInit    = netDeviceInit,
	.DeviceExit    = netDeviceExit,
};

void NetDeviceRegister(void)
{
	RegisterInputDev(&g_tNetInputOpr);
}



